package com.witframework.dynoengine.render.page;

import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.util.WebUtils;

import com.witframework.core.persistence.JdbcTools;
import com.witframework.core.persistence.PageSortModel;
import com.witframework.dynoengine.AbstractParamSetObject;
import com.witframework.dynoengine.Converter;
import com.witframework.dynoengine.MetaFactory;
import com.witframework.dynoengine.model.WitMetaColumn;
import com.witframework.dynoengine.model.WitMetaTable;
import com.witframework.dynoengine.render.ColumnComparator;
import com.witframework.dynoengine.render.MiniTemplator;
import com.witframework.dynoengine.render.Renderer;
import com.witframework.dynoengine.render.TempleteFactory;
import com.witframework.dynoengine.render.form.DateRender;
import com.witframework.dynoengine.render.form.FormFieldRender;
import com.witframework.dynoengine.render.form.InputRender;
import com.witframework.dynoengine.render.formater.CellFormat;
import com.witframework.dynoengine.render.formater.DefaultCellFormat;
import com.witframework.dynoengine.render.selector.DefaultOptionSelectorRender;
import com.witframework.dynoengine.render.selector.SelectorRender;
import com.witframework.util.StringTools;

public class ListDataPageRender extends AbstractParamSetObject implements Renderer {	
	public String render() {	
		String tableId=(String)getParameter(Renderer.PARAM_tableId);
		String tableName=(String)getParameter(Renderer.PARAM_tableName);
		WitMetaTable mt=MetaFactory.getInstance().getMetaTableById(tableId);
		if(tableName==null){			
			tableName=mt.getTableName();
		}
		HttpServletRequest httpRequest=(HttpServletRequest)getParameter(Renderer.PARAM_httpRequest);		
		//FIXME delete me
		MetaFactory.getInstance().refresh();
		mt=MetaFactory.getInstance().getMetaTableByName(tableName);
		MiniTemplator templator;
		String searcher=searcherGenerator(tableName);
		if(searcher.length()>0)//具有搜索栏
			templator=TempleteFactory.getInstance().getMiniTemplator("list/list.page","hasSearch");
		else
			templator=TempleteFactory.getInstance().getMiniTemplator("list/list.page");
		templator.setVariableOpt("tableName", tableName);
		templator.setVariableOpt("tableTitle",StringUtils.isNotEmpty(mt.getTableTitle())?mt.getTableTitle():tableName);
		templator.setVariableOpt("contextPath", httpRequest.getContextPath());
		List<WitMetaColumn> metColumnList=MetaFactory.getInstance().getMetaFileds(tableName);
		WitMetaColumn[] metColumns=metColumnList.toArray(new WitMetaColumn[0]);
		Arrays.sort(metColumns,new ColumnComparator());//按照排序字段排序	
		templator.setVariableOpt("search_items", searcher);		

		if(templator.blockExists("column_title_block")){
			for(WitMetaColumn wmc:metColumns){
				if(StringTools.parseBoolean(wmc.getIsListable())
						&&!wmc.getColumnName().equalsIgnoreCase("id")
						){
									
					String column_title=wmc.getColumnTitle();					
					if(StringUtils.isEmpty(column_title)){
						column_title=wmc.getColumnName();
					}
					templator.setVariableOpt("column_title", column_title);
					String isSortable=wmc.getIsSortable();
					if(StringTools.parseBoolean(isSortable)){
						templator.setVariableOpt("nosort", "");
					}else{
						templator.setVariableOpt("nosort", "nosort");
					}
					templator.addBlock("column_title_block");
				}
			}			
		}	
		
		String pagination_pageno=httpRequest.getParameter("pagination_pageno");
		String pagination_pagesize=httpRequest.getParameter("pagination_pagesize");
		if(StringUtils.isEmpty(pagination_pageno)){
			pagination_pageno="1";
		}
		if(StringUtils.isEmpty(pagination_pagesize)){
			pagination_pagesize="10";
		}
		
		PageSortModel psm = new PageSortModel();
		psm.setPageSize(Integer.parseInt(pagination_pagesize));
		psm.setPageNo(Integer.parseInt(pagination_pageno));		
		//查询数据
		List<Map> dataList;
		List objects=new ArrayList();
		String where=createWhere(tableName,objects);
		if(objects.size()>0)
			dataList=JdbcTools.pageQuery(psm, "SELECT * FROM "+tableName+" WHERE "+where,objects.toArray(new Object[0]));	
		else
			dataList=JdbcTools.pageQuery(psm, "select * from "+tableName);	
		if(templator.blockExists("row_block")){
			for(Map data:dataList){
				String identification_string="";
				for(WitMetaColumn wmc:metColumns){
					String column_name=wmc.getColumnName().toUpperCase();	
					Object column_value=data.get(column_name);
					String formatClass=wmc.getFormatClass();						
					CellFormat cf=null;
					if(StringUtils.isNotEmpty(formatClass)){
						try {
							cf=(CellFormat)Class.forName(formatClass).newInstance();								
						} catch (Exception e) {								
						}
					}
					if(cf==null){
						cf=new DefaultCellFormat();
					}
					String cellText=cf.parse(column_value);
					if( StringTools.parseBoolean(wmc.getIsPkey()) ){
						if(identification_string.length()>0) identification_string+="&";
						identification_string+=column_name+"="+cellText;
					}
					if(StringTools.parseBoolean(wmc.getIsListable())&&!wmc.getColumnName().equalsIgnoreCase("id")	){							
						templator.setVariableOpt("column_value", cellText);
						templator.addBlock("column_block");
						
					}
				}
				templator.setVariableOpt("identification_string", identification_string+"&action=update");
				templator.addBlock("row_block");
			}
		}
		templator.setVariableOpt("total_size",String.valueOf(psm.getTotalRows()));
		templator.setVariableOpt("pagination_pageno",String.valueOf(psm.getPageNo()));
		templator.setVariableOpt("pagination_pagesize",pagination_pagesize);
		templator.setVariableOpt("pagination_pagecount",String.valueOf(psm.getPageCount()));
		return templator.generateOutput();//StringTools.compressHtml
		
	}
	//生成搜索工具栏
	private String searcherGenerator(String tableName){
		String searcher="";
		HttpServletRequest httpRequest=(HttpServletRequest)getParameter(Renderer.PARAM_httpRequest);	
		List<WitMetaColumn> metColumns=MetaFactory.getInstance().getMetaFileds(tableName);
		for(WitMetaColumn wmc:metColumns){
			if(StringTools.parseBoolean(wmc.getIsQueryable())){
				Renderer render=null;
				String selectType=wmc.getSelectType();
				if(StringUtils.isEmpty(selectType) ){
					int columnSize=wmc.getColumnSize();
					int columnType=wmc.getColumnType();
					if(Types.DATE==columnType||Types.TIMESTAMP==columnType||Types.TIME==columnType){
						render=new DateRender();					
					}else{
						render=new InputRender();							
					}
					if(StringTools.parseBoolean(wmc.getIsPkey())||!StringTools.parseBoolean(wmc.getIsDisplayable()))
							render.setParameter(FormFieldRender.PARAM_type,"readonly");
					render.setParameter(FormFieldRender.PARAM_name, "_"+wmc.getColumnName());
					render.setParameter(FormFieldRender.PARAM_editable,wmc.getIsEditable());
					render.setParameter(FormFieldRender.PARAM_size,wmc.getColumnSize()>20?20:wmc.getColumnSize());
					render.setParameter(FormFieldRender.PARAM_tiptext, wmc.getTipText());
					render.setParameter(FormFieldRender.PARAM_validation, wmc.getValidation());
					
					String data=httpRequest.getParameter("_"+wmc.getColumnName());
					if(data!=null)
						render.setParameter(FormFieldRender.PARAM_value, data);						
				}else if(selectType.equalsIgnoreCase("select")||selectType.equalsIgnoreCase("mselect")){
					render=new DefaultOptionSelectorRender();
					render.setParameter(SelectorRender.PARAM_parameter, wmc.getSelectParam());
				}else{
					
				}
				searcher+=wmc.getColumnTitle()+":"+render.render();				
			}	
		}
		return searcher;	
	}
	//生成数据查询语句的条件子语句
	private String createWhere(String tableName,List ol){
		String where="";
		HttpServletRequest httpRequest=(HttpServletRequest)getParameter(Renderer.PARAM_httpRequest);		
		Map<String, String> parameters = WebUtils.getParametersStartingWith(httpRequest, "_");
		for( Iterator iter=parameters.keySet().iterator();iter.hasNext();){
			String columnName=(String)iter.next();
			String columnValue=(String)parameters.get(columnName);
			WitMetaColumn wmc=MetaFactory.getInstance().getMetaFiled(tableName, columnName);
			if(StringUtils.isNotEmpty(columnValue)&&wmc!=null){
				if(where.length()>0) where+=" AND ";
				Object ov=Converter.convertToObject(wmc.getColumnType(), columnValue);
				if(ov instanceof String){
					where+=columnName+" LIKE ?";	
					ov=ov+"%";
				}
				else
					where+=columnName+" = ?";	
				ol.add(ov);		
			}
		}
		return where;
	}
}
